// https://www.lintcode.com/problem/insert-five/

public class Solution {
    /**
     * @param a: A number
     * @return: Returns the maximum number after insertion
     */
    public int InsertFive(int a) {
        // write your code here
        int ret = 0;
        List<Integer> digits = new ArrayList<>();
        int aa = Math.abs(a);
        if (aa == 0) {
            digits.add(0);
        } else {
            while (aa > 0) {
                digits.add(aa % 10);
                aa /= 10;
            }
        }
        boolean inserted = false;
        for (int i = digits.size() - 1; i >= 0; --i) {
            int d = digits.get(i);
            if (a >= 0) {
                if ((d < 5) && (!inserted)) {
                    ret = ret * 10 + 5;
                    inserted = true;
                }
            } else {
                if ((d > 5) && (!inserted)) {
                    ret = ret * 10 + 5;
                    inserted = true;
                }
                
            }
            ret = ret * 10 + d;
        }
        if (!inserted) {
            ret = ret * 10 + 5;
        }
        return (a >= 0) ? ret : (-ret);
    }
}